/*
 * @Description:
 * @Author: wangqian
 * @LastEditors: wangqian
 * @Date: 2021-03-23 14:05:36
 * @LastEditTime: 2021-05-11 10:04:09
 */
import { Tree } from 'ant-design-vue';
import { isNil, cloneDeep } from 'lodash';
import { depthEach } from '@/utils/tree';
import TreeLayout from './TreeLayout';
import fonts from '../iconfont/iconfont.json';
const graphUtil = {
  /**
   * 当前节点是否有某个state状态
   * @param {Object} node 节点对象
   * @param {String} state
   */
  hasState(node, state) {
    const states = node._cfg.states;
    return states.includes(state);
  },
  /**
   * 获取iconfont
   * @param {String} type
   */
  getIcon(type) {
    try {
      const icons = fonts.glyphs.map(icon => {
        return {
          name: icon.name,
          unicode: String.fromCodePoint(icon.unicode_decimal), // `\\u${icon.unicode}`,
        };
      });
      const matchIcon = icons.find(icon => {
        return icon.name === type;
      }) || { unicode: '', name: 'default' };
      return matchIcon.unicode;
    } catch (err) {
      return '';
    }
  },
  /**
   * @description: 缓存节点信息
   * @param {*} nodes
   * @return {*}
   */
  cacheNodePositions(nodes) {
    const positionMap = {};
    const nodeLength = nodes.length;
    for (let i = 0; i < nodeLength; i++) {
      const node = nodes[i].getModel();
      positionMap[node.id] = {
        x: node.x,
        y: node.y,
        level: node.level,
      };
    }
    return positionMap;
  },
};
export default graphUtil;

// 创建图谱数据
export function createGraphData(nodes, links) {
  const mockData = {
    caseList: [],
    elementList: [],
  };
  // 交集
  function getIntersection(arr1, arr2) {
    return arr1.filter(val => arr2.indexOf(val) > -1);
  }
  nodes.forEach(item => {
    if (item.class === 'case') {
      mockData.caseList.push(item);
    } else {
      mockData.elementList.push(item);
    }
  });
  mockData.elementList.forEach(item => {
    let list = [];
    links.forEach(o => {
      if (o.source === item.id) {
        list.push(o.target);
      } else if (o.target === item.id) {
        list.push(o.source);
      }
    });
    item.caseList = list;
  });
  let eleSize = mockData.elementList.length;
  let temIndex = 0;
  let newList = [];
  mockData.elementList.forEach((item, index) => {
    for (let i = index + 1; i < eleSize; i++) {
      let list = getIntersection(item.caseList, mockData.elementList[i].caseList);
      if (list.length > 0) {
        newList.push({
          source: item.id,
          target: mockData.elementList[i].id,
          id: temIndex,
          label: `${list.length}起`,
          list: list.toString(),
        });
        temIndex++;
      }
    }
  });

  return {
    edgeList: newList,
    nodeList: mockData.elementList,
  };
}

// 获取根节点
export function getRootNode(nodes, x, y) {
  const node = { value: null };
  node.value = nodes.sort((a, b) => b.caseNum - a.caseNum)[0];
  node.value.level = 0;
  node.value.x = x || 300;
  node.value.y = y || 300;
  return node.value;
}

export const effectiveEdges = [];
export const nodesMap = {};

// 获取下级数据
export function getSubordinateData(node, edges, nodes) {
  const nodeList = [];
  const edgeList = [];
  nodes.forEach(o => (nodesMap[o.id] = o));
  edges.forEach(e => {
    const currentId = [e.source, e.target].find(o => node.id === o);
    edgeList.push(e);

    if (currentId) {
      const id = [e.source, e.target].find(o => node.id !== o);
      if (isNil(nodesMap[id].level)) {
        nodesMap[id].level = node.level + 1;
        nodeList.push(nodesMap[id]);
        effectiveEdges.push(e);
      }
    }
  });

  return {
    nodeList,
    edgeList,
  };
}
//--------------------------- tree layout start -----------------------------//
// 图转树
export function graph2tree(nodeList) {
  const root = getRootNode(nodeList);
  const tree = transformTree(root, effectiveEdges);
  console.log('effectiveEdges', effectiveEdges.length);
  return tree;
}

/**
 * 1，tree id pid 有方向
 * 2，graph target source 也有方向
 * 3，点击节点加载与其直接相关联的节点，默认将相关联的节点当作target
 */
function transformTree(parent, list) {
  const children = [];
  list &&
    list.forEach((e, i) => {
      if ([list[i].target, list[i].source].find(o => o === parent.id)) {
        console.log('parent', parent.id);

        const currentId = [list[i].target, list[i].source].find(o => o !== parent.id);
        const currentNode = nodesMap[currentId];
        console.log('length');
        const item = transformTree(currentNode, [...list].splice(1, i));
        children.push(item);
      }
    });

  if (children.length) {
    parent.children = children;
  }

  return parent;
}

let treeData_ = null;
export const addNodesForTree = (nodeList, node, children) => {
  const root = getRootNode(nodeList);
  treeData_ = treeData_ || root;
  depthEach([treeData_], item => {
    if (item.id === node.id) {
      item.children = children;
    }
  });
  TreeLayout.vertical(treeData_, 50, 50, 1500, 800);
  return treeData_;
};

//--------------------------- tree layout end -----------------------------//
